package xxdsqljob

import grails.converters.JSON
import mianThread.XxsqlJobThread
import xxdsqljobDB.ExcelUtil
import xxdsqljobDB.ResultModel
import xxdsqljobDB.XxdsqljobUtil

import java.text.SimpleDateFormat

class XxdsqljobController {

    def dataSource

    def index() {
        def resultMap = ResultModel.resultModel()
        def jobName = params.jobName?:""

        try {
            def c = JobCfg.createCriteria()
            def jobs = c.list {
                if(jobName && jobName.indexOf("'") <0){
                    like("jobName","%${jobName}%")
                }
            }
            resultMap.put(ResultModel.DATA,jobs)
            resultMap.put(ResultModel.COUNT,jobs.size())
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def addJobCfg(){
        def resultMap = ResultModel.resultModel()
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            def jobName = params.jobName?:""
            JobCfg jobCfg
            if(jobName){
                  jobCfg = JobCfg.findByJobName(jobName)
            }

            if(jobCfg){
                resultMap.put(ResultModel.CODE,ResultModel.CODE_402)
                resultMap.put(ResultModel.MSG,ResultModel.MSG_402)
            }else {
                jobCfg = JobCfg.newInstance()
                jobCfg.setJobName(jobName)
                jobCfg.setInitTime(simpleDateFormat.parse(params.initTime?:""))
                jobCfg.setPeriod(Long.parseLong(params.period?:""))
                jobCfg.setUnit(params.unit?:"")
                jobCfg.setActive(params.active?:"Y")
                jobCfg.setState(params.state?:"")
                jobCfg.setUploadPath(params.uploadPath?:"")
                jobCfg.setCreator(params.lmUser?:"")
                jobCfg.save(flush: true)
                resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
                resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
            }
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_400)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def getOne(){
        def resultMap = ResultModel.resultModel()
        try {
            JobCfg jobCfg = JobCfg.get(Long.parseLong(params.jobId?:"-1"))
            resultMap.put(ResultModel.DATA,jobCfg)
            resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def editJobCfg(){
        def resultMap = ResultModel.resultModel()
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            JobCfg jobCfg = JobCfg.get(Long.parseLong(params.id?:"-1"))
            if(jobCfg){
                jobCfg.setJobName(params.jobName?:"")
                jobCfg.setInitTime(simpleDateFormat.parse(params.initTime?:""))
                jobCfg.setPeriod(Long.parseLong(params.period?:""))
                jobCfg.setUnit(params.unit?:"")
                jobCfg.setUpdater(params.lmUser?:"")
                jobCfg.setUploadPath(params.uploadPath?:"")
                jobCfg.save(flush: true)
            }
            resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_400)
            e.printStackTrace()
        }
        render resultMap as JSON
    }


    def jobLogList(){
        def resultMap = ResultModel.resultModel()
        def jobName = params.jobName?:""
        def jobId = Long.parseLong(params.jobId?:"-1")
        def state = params.state?:""
        def page = Integer.parseInt(params.page?:"1")
        def max  = Integer.parseInt(params.limit?:"20")

        try {
            def c = JobHis.createCriteria()
            def jobs = c.list(offset: (page-1)*max,max: max) {
                eq("jobId",jobId)
                if(state){
                    eq("state",state)
                }
                order("logDated","desc")
            }

            def count =  JobHis.countByJobIdAndStateLike(jobId,"%${state}%")

            resultMap.put(ResultModel.DATA,jobs)
            resultMap.put(ResultModel.COUNT,count)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def deleteLog(){
        def sql = "delete from Job_His where job_id = ? and log_Dated <  ? "
        def resultMap = ResultModel.resultModel()
        try {
            def jobId = Long.parseLong(params.jobId?:"-1")
            def days = Integer.parseInt(params.clearType?:"0")
            Calendar calendar = Calendar.getInstance()
            calendar.setTime(new Date())
            calendar.add(Calendar.DAY_OF_YEAR,-days)
            def db = new groovy.sql.Sql(dataSource)
            db.executeUpdate(sql,[jobId, XxdsqljobUtil.getSqlTime(calendar.getTime())])

            resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_400)
            e.printStackTrace()
        }
        render resultMap as JSON
    }


    def stopJob(){
        def resultMap = ResultModel.resultModel()
        try {
            def jobId = Long.parseLong(params.jobId?:"-1")
            JobCfg jobCfg = JobCfg.get(jobId)
            def flag = false
            if(jobCfg){
                flag =   XxsqlJobThread.closeJob(jobCfg)
                if(flag){
                    resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
                    resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
                }else{
                    resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
                    resultMap.put(ResultModel.MSG,"停止任务失败，请稍后重试!")
                }
            }else{
                resultMap.put(ResultModel.CODE,ResultModel.CODE_401)
                resultMap.put(ResultModel.MSG,ResultModel.MSG_401)
            }
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_400)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def restart(){
        def resultMap = ResultModel.resultModel()
        try {
            def jobId = Long.parseLong(params.jobId?:"-1")
            JobCfg jobCfg = JobCfg.get(jobId)
            def flag = false
            if(jobCfg && jobCfg.active == "Y"){
                flag =  XxsqlJobThread.closeJob(jobCfg)
                if(flag){
                    flag = XxsqlJobThread.doJob(jobCfg)
                    if(flag){
                        resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
                        resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
                    }else {
                        resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
                        resultMap.put(ResultModel.MSG,"启动任务失败，请稍后重试!")
                    }
                }else{
                    resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
                    resultMap.put(ResultModel.MSG,"停止任务失败，请稍后重试!")
                }
            }else{
                resultMap.put(ResultModel.CODE,ResultModel.CODE_401)
                resultMap.put(ResultModel.MSG,"重启任务失败，任务未激活，或稍后重试!")
            }
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_400)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def recovery(){
        def resultMap = ResultModel.resultModel()
        try {
            def jobCfgList = JobCfg.findAllByActive("Y")
            jobCfgList.each {
                XxsqlJobThread.doJob(it)
            }
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_400)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def stopAll(){
        def resultMap = ResultModel.resultModel()
        try {
            def jobCfgList = JobCfg.findAllByActive("Y")
            jobCfgList.each {
                XxsqlJobThread.closeJob(it)
            }
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_400)
            e.printStackTrace()
        }
        render resultMap as JSON
    }
    /**
     * 激活状态，
     * @return
     */
    def active(){
        def resultMap = ResultModel.resultModel()
        try {
            def jobId = Long.parseLong(params.jobId?:"-1")
            def active = params.active?:"N"
            JobCfg jobCfg = JobCfg.get(jobId)
            def flag = false
            if(jobCfg){
                if(active.equals("N")){
                    flag = XxsqlJobThread.closeJob(jobCfg)
                }else{
                    flag = true
                }
                if(flag){
                    XxdsqljobUtil.updateJobCfgActive(jobId,active,params.lmUser?:"")
                    resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
                    resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
                }else{
                    resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
                    resultMap.put(ResultModel.MSG,"停止任务失败，请稍后重试!")
                }
            }else{
                resultMap.put(ResultModel.CODE,ResultModel.CODE_401)
                resultMap.put(ResultModel.MSG,ResultModel.MSG_401)
            }
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_400)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_400)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def queryMenu(){
        def resultMap = ResultModel.resultModel()
        def menuName = params.menuName?:""
        def jobId = Long.parseLong(params.jobId?:"-1")
        def result = []
        try {
            if(  menuName.indexOf("'")<0){
                result =  XxdsqljobUtil.queryMenu(jobId,menuName)
            }
            resultMap.put(ResultModel.DATA,result)
            resultMap.put(ResultModel.COUNT,result.size())
            resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }


    def queryUser(){
        def resultMap = ResultModel.resultModel()
        def user = params.user?:""
        def jobId = Long.parseLong(params.jobId?:"-1")
        def result = []
        try {
            if(user.indexOf("'")<0){
                result =  XxdsqljobUtil.queryUser(jobId,user)
            }
            resultMap.put(ResultModel.DATA,result)
            resultMap.put(ResultModel.COUNT,result.size())
            resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def job2user(){
        def resultMap = ResultModel.resultModel()
        def userId = Long.parseLong(params.userId?:"-1")
        def jobId = Long.parseLong(params.jobId?:"-1")
        def checkFlag = Boolean.parseBoolean(params.checkFlag?:"false")
        def result = []
        try {
            JobEmailUser jobEmailUser  = JobEmailUser.findByJobIdAndUserId(jobId,userId)
            if(checkFlag){
                if(!jobEmailUser){
                    jobEmailUser = JobEmailUser.newInstance(jobId:jobId,userId:userId)
                    jobEmailUser.save(flush: true)
                }
            }else{
                if(jobEmailUser){
                    jobEmailUser.delete(flush: true)
                }
            }
            resultMap.put(ResultModel.DATA,result)
            resultMap.put(ResultModel.COUNT,result.size())
            resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def job2report(){
        def resultMap = ResultModel.resultModel()
        def rptId = Long.parseLong(params.rptId?:"-1")
        def jobId = Long.parseLong(params.jobId?:"-1")
        def checkFlag = Boolean.parseBoolean(params.checkFlag?:"false")
        def result = []
        try {
            JobReport job2Report  = JobReport.findByRptIdAndJobId(rptId,jobId)
            if(checkFlag){
                if(!job2Report){
                    job2Report = JobReport.newInstance(jobId:jobId,rptId:rptId)
                    job2Report.save(flush: true)
                }
            }else{
                if(job2Report){
                    job2Report.delete(flush: true)
                }
            }
            resultMap.put(ResultModel.DATA,result)
            resultMap.put(ResultModel.COUNT,result.size())
            resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def job2reportSql(){
        def resultMap = ResultModel.resultModel()
        def rptId = Long.parseLong(params.RPT_ID?:"-1")
        def jobId = Long.parseLong(params.JOB_ID?:"-1")
        def field = params.field?:""
        try {
            JobReport job2Report  = JobReport.findByRptIdAndJobId(rptId,jobId)
            if(job2Report && field){
                if(field.equals("SQL_IDS")){
                    job2Report.setSqlIds(params.SQL_IDS?:"")
                }else if(field.equals("PARAM")){
                    job2Report.setParam(params.PARAM?:"")
                }
                job2Report.save(flush: true)
                resultMap.put(ResultModel.CODE,ResultModel.CODE_0)
                resultMap.put(ResultModel.MSG,ResultModel.MSG_0)
            }else {
                resultMap.put(ResultModel.CODE,ResultModel.CODE_401)
                resultMap.put(ResultModel.MSG,"请先选择Report")
            }

        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def jobReportFile(){
        def sfDayTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        def resultMap = ResultModel.resultModel()
        def jobName = params.jobName?:""
        def reportName = params.reportName?:""
        def dateStr = params.date?: sfDayTime.format(new Date())[0..9]
        def startDate = sfDayTime.parse(String.valueOf("${dateStr} 00:00:00"))
        def endDate   = sfDayTime.parse(String.valueOf("${dateStr} 23:59:59"))
        def page = Integer.parseInt(params.page?:"1")
        def max  = Integer.parseInt(params.limit?:"20")

        try {
            def c = JobReportFile.createCriteria()
            def jobs = c.list() {
                if(jobName && jobName.indexOf("'") <0){
                    like("fileName","%${jobName}%")
                }
                if(reportName && reportName.indexOf("'") <0){
                    like("fileName","%${reportName}%")
                }
                between("dateCreated",startDate,endDate)
                order("dateCreated","desc")
            }

            def count =  jobs.size()
            resultMap.put(ResultModel.DATA,jobs)
            resultMap.put(ResultModel.COUNT,count)
        }catch (Exception e){
            resultMap.put(ResultModel.CODE,ResultModel.CODE_300)
            resultMap.put(ResultModel.MSG,ResultModel.MSG_300)
            e.printStackTrace()
        }
        render resultMap as JSON
    }

    def dowLoadFile(){
        def fileName = ExcelUtil.EncodingFileName(request,params.fileName?:"dowLoadFile")
        def tempFile = params.tempFile?:"tempFile"
        ExcelUtil.DownLoadExcel2007(response,fileName,tempFile)
        return
    }
}
